#include "tcp_network.h"
#include "game_server.h"
#include <iostream>

using namespace std;

TcpNetwork::TcpNetwork(struct event_base* event_base)
	: NetworkBase(event_base)
{
	
}

void TcpNetworkSession::Send(const char * data, size_t length)
{
	static MessageBuffer buf(8192);
	buf.Reset();
	uint32_t ulength = length;
	string str(data, length);
	xorFunc(str);
	buf << ulength << str;
	SendBase((const char *)buf.GetReadPointer(), buf.GetActiveSize());
}

void TcpNetworkSession::Send(const std::string & str)
{
	Send(str.c_str(), str.size());
}



int TcpNetworkSession::HandleMessage()
{
	int ret = -1;
	while (1)
	{
		if (_status == HEADER_STATUS)
		{
			if (_rbuf.GetActiveSize() < sizeof(uint32_t))
			{
				break;
			}
			_rbuf >> _proto_length;
			_status = BODY_STATUS;
		}
		if (_status == BODY_STATUS)
		{
			if (_rbuf.GetActiveSize() < _proto_length)
			{
				break;
			}
			string proto_data = _rbuf.Read(_rbuf.GetActiveSize());
			xorFunc(proto_data);
			cout << "read = " << proto_data << endl;
			_jpacket.Decode(proto_data);

			//do something
			int t_ret = Singleton<GameServer>::Instance()->Dispatch(this);
			ret = (ret == 0) ? 0 : t_ret;

			_status = HEADER_STATUS;
		}
	}
	_rbuf.Normalize();
	return ret;
}

void TcpNetworkSession::xorFunc(string & str)
{
	const int KEY = 13;
	int strLen = (str.length());
	char *cString = (char*)(str.c_str());

	for (int i(0); i < strLen; i++)
	{
		*(cString + i) = (*(cString + i) ^ KEY);
	}
}
int TcpNetworkSession::BeforeDestroy()
{
	Singleton<GameServer>::Instance()->Delete<FD_KEY>(_fd);
	return 0;
}
;

NetworkSessionBase * TcpNetwork::NewSession(int fd)
{
	return new TcpNetworkSession(_event_base);
}
